package com.chen.controller;

import cn.hutool.core.util.ObjectUtil;
import com.chen.dto.ChooseSubDTO;
import com.chen.dto.ImportDTO;
import com.chen.dto.SubjectDTO;
import com.chen.service.CourseService;
import com.chen.service.ExamPaperService;
import com.chen.service.GradeService;
import com.chen.service.SubjectService;
import com.chen.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 试题接口
 */
@Controller
@RequestMapping("/subject")
public class SubjectController {

    @Autowired
    private SubjectService subjectService;

    // 班级信息
    @Autowired
    private GradeService gradeService;

    // 科目
    @Autowired
    private CourseService courseService;
    @Autowired
    private ExamPaperService examPaperService;


    /**
     * 查询试题集合
     * @param subjectId    查询条件
     * @param courseId
     * @param gradeId
     * @param startPage
     * @param pageShow
     * @param handAdd  标识 是否为需要进行手动添加试题到试卷而发起的请求
     * @param examPaperId
     * @param session
     * @return
     */
    @GetMapping("/subjects")
    public ModelAndView getTeachers(
            @RequestParam(value="subjectId", required=false) Integer subjectId,
            @RequestParam(value="courseId", required=false) Integer courseId,
            @RequestParam(value="gradeId", required=false) Integer gradeId,
            @RequestParam(value="startPage", required=false, defaultValue="1") Integer startPage,
            @RequestParam(value="pageShow", required=false, defaultValue="10") Integer pageShow,
            @RequestParam(value="handAdd", required=false) Integer handAdd,
            @RequestParam(value="examPaperId", required=false) Integer examPaperId,
            HttpSession session) {
        ModelAndView model = new ModelAndView();
        model.setViewName("/admin/subjects");

        //计算当前查询起始数据索引
        int startIndex = (startPage-1) * pageShow;
        List<SubjectVO> subjects = subjectService.pageList(subjectId, courseId, gradeId, startIndex, pageShow);
        model.addObject("subjects", subjects);

        //获取试题总量
        Long subjectTotal = subjectService.count();
        //计算总页数
        Long pageTotal = 1L;
        if (subjectTotal % pageShow == 0)
            pageTotal = subjectTotal / pageShow;
        else
            pageTotal = subjectTotal / pageShow + 1;
        model.addObject("pageTotal", pageTotal);
        model.addObject("pageNow", startPage);

        //是否为需要进行手动添加试题到试卷而发起的请求
        if (handAdd != null && handAdd == 1) {
            model.addObject("handAdd", "1");
        }
        //如果是手动添加试题到试卷，则需要返回试卷编号, 且返回当前已经选择试题数量
        if (examPaperId != null) {
            model.addObject("examPaperId", examPaperId);
            List<String> ids = (List<String>) session.getAttribute("ids");
            if (ids == null) {
                model.addObject("choosed", 0);
            } else {
                model.addObject("choosed", ids.size());
            }
        }
        return model;
    }

    /**
     * 为试卷添加试题
     * @param dto
     * @return
     */
    @ResponseBody
    @PostMapping("getChooseSubId")
    public String getChooseSubId(ChooseSubDTO dto) {
        Integer i = subjectService.saveExamPaper(dto);
        if (i == 0) {
            return "f-exists-" + dto.getSubjectId();
        }
        return String.format("编号为 %s 的试题添加成功", dto.getSubjectId());
    }


    /**
     * 添加试题
     * @return
     */
    @GetMapping("/preAddSubject")
    public ModelAndView preAddStudent() {
        ModelAndView model = new ModelAndView();
        model.setViewName("/admin/subject-test");
        List<GradeVO> grades = gradeService.findAllGrade();
        model.addObject("grades", grades);
        model.addObject("courses", courseService.findAll());
        return model;
    }

    /**
     * 进入修改试题界面
     * @param subjectId
     * @return
     */
    @GetMapping("/edit/{subjectId}")
    public ModelAndView edit(@PathVariable("subjectId") Integer subjectId) {
        ModelAndView model = new ModelAndView();
        model.setViewName("/admin/subject-test");
        List<GradeVO> grades = gradeService.findAllGrade();
        model.addObject("grades", grades);
        model.addObject("courses", courseService.findAll());
        model.addObject("subject", subjectService.getSubjectById(subjectId));
        return model;
    }

    /**
     * 修改试题信息
     * @param subject
     * @return
     */
    @ResponseBody
    @PostMapping("/updateSubject")
    public String updateSubject(SubjectDTO subject) {
        int row = subjectService.updateSubject(subject);
        if (row > 0) {
            return "试题修改成功";
        } else {
            return "试题修改失败";
        }
    }


    /**
     * 添加试题信息
     * @param subject
     * @return
     */
    @ResponseBody
    @PostMapping("/addSubject")
    public String addSubject(SubjectDTO subject) {
        int row = subjectService.addSubject(subject);
        if (row > 0) {
            return "试题添加成功";
        } else {
            return "试题添加失败";
        }
    }

    /**
     * 删除试题
     * @param subjectId
     * @throws IOException
     */
    @ResponseBody
    @PostMapping("/delSubject")
    public String delSubject(@RequestParam("subjectId") Integer subjectId) {
        int row = subjectService.delById(subjectId);
        if (row > 0) {
            return "t";
        } else {
            return "f";
        }
    }

    /**
     * 进入导入
     * @return
     */
    @RequestMapping(value="/initImport")
    public ModelAndView initImportExcel() {
        ModelAndView model = new ModelAndView("/admin/importSubject");
        //获取所有科目
        List<CourseVO> courses = courseService.findAll();
        //获取所有年级
        List<GradeVO> grades = gradeService.findAllGrade();
        //获取所有试卷名称
        List<ExamPaperVO> examPapers = examPaperService.findAll();

        model.addObject("courses", courses);
        model.addObject("grades", grades);
        model.addObject("examPapers", examPapers);

        return model;
    }

    /**
     * 试题导入 处理
     */
    @PostMapping("/dispatcherUpload")
    public ModelAndView dispatcherUpload(ImportDTO importDTO) {
        ModelAndView model = new ModelAndView("/admin/suc");
        // 导入数据
        try{
            subjectService.importData(importDTO);
        }catch (Exception e) {
            e.printStackTrace();
        }
        return model;
    }




    /**
     * 手动添加试题
     * 手动将选择的试题添加到指定试卷中  -- 正式添加处理
     * @param examPaperId 试卷编号
     * @param session
     * @param response
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value="/handAdd", method={RequestMethod.GET, RequestMethod.POST})
    public String isHandAddSubjectToExamPaper(
            @RequestParam(value="examPaperId") Integer examPaperId,
            HttpSession session,
            HttpServletResponse response) throws Exception {
        return "试题已成功添加到试卷中！";
    }



}
